<template>
  <el-card shadow="never" class="basic_info_body sourcing-table-card">
    <h3 slot="header">填写商品信息</h3>
    <el-backtop target="#app .i-layout-content-main">
      <i class="el-icon-top"></i>
    </el-backtop>
    <el-card class="title_wrap">
      <el-row type="flex" justify="center" align="middle">
        <div>{{ category.name }}</div>
        <div>
          <el-button type="text" @click="handleReEditCategory"
            >编辑类目</el-button
          >
        </div>
        <template v-if="!finishedFlag">
          <el-button
            v-if="!generateCode.isGenerate"
            type="primary"
            size="mini"
            @click="handleGenerateCode"
            :loading="endingBtnLoading"
            >生成代码</el-button
          >
          <el-button
            v-if="generateCode.isGenerate"
            type="primary"
            @click="handleSubmitData"
            :loading="endingBtnLoading"
            >保存基本信息</el-button
          >
          <el-button
            v-if="generateCode.isGenerate"
            @click="handleToStep2"
            icon="el-icon-bottom"
            circle
          ></el-button>
        </template>
      </el-row>
    </el-card>
    <!-- 基础属性 -->
    <el-row class="basic_info_form_body">
      <BasicInfoForm
        ref="basicInfoForm"
        :categoryUuid="category.uuid"
        :isGenerateCode="generateCode.isGenerate"
        :productTypeOptions="basicInfo.productTypeOptions"
        @getFormData="getFormDataFn"
      />
    </el-row>
    <!-- 销售属性 -->
    <el-row class="sale_attribute_body">
      <SaleAttribute
        v-show="saleAttributeLoadFinished"
        ref="saleAttr"
        :specList="specList"
        :isGenerateCode="generateCode.isGenerate"
        :categoryUuid="category.uuid"
        @getSpecList="getSpecListFn"
      />
    </el-row>
    <div ref="attributeBody" v-show="generateCode.isGenerate">
      <!-- 管理属性 -->
      <el-row class="manage_attribute_body">
        <ManageAttribute
          ref="manageAttr"
          :basicInfoList="generateCode.basicInfoList"
          :manageInfoList="generateCode.manageInfoList"
          :marketingInfoList="generateCode.marketingInfoList"
          :taxInfoList="generateCode.taxInfoList"
          :logisticsInfoList="generateCode.logisticsInfoList"
          :isFinished="finishedFlag"
          :productType="generateCode.formData.productType"
          @getManageAttributeData="getManageAttributeDataFunc"
        />
      </el-row>
      <!-- SKU属性 -->
      <el-row class="sku_attribute_body">
        <SkuAttribute
          ref="skuAttr"
          :packageList="generateCode.packageList"
          @getPackageList="getPackageListFunc"
        />
      </el-row>
    </div>
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import BasicInfoForm from './basicInfoForm';
import SaleAttribute from './saleAttribute';
import ManageAttribute from './manageAttribute';
import SkuAttribute from './skuAttribute';
import { isResponseSuccess } from '@/utils/bizUtils';
import { getLoadingFn } from '@/utils/loading';
import { setWarningDialogFunc } from '@/pages/commodity/modules/utils/manageInfoRequireUtils';

export default {
  components: {
    BasicInfoForm,
    SaleAttribute,
    ManageAttribute,
    SkuAttribute
  },
  data () {
    return {
      category: {
        uuid: '',
        name: ''
      },
      basicInfo: {
        productTypeOptions: []
      },
      specList: [],
      generateCode: {
        formData: {},
        specList: [],
        isGenerate: false,
        templateUuid: '',
        basicInfoList: [],
        manageInfoList: [],
        marketingInfoList: [],
        taxInfoList: [],
        logisticsInfoList: [],
        sceneInfoList: [],
        packageList: {}
      },
      submitCodeList: {},
      finishedFlag: false,
      spuNo: '',
      productUuid: '',
      endingBtnLoading: false,
      saleAttributeLoadFinished: false
    };
  },
  mounted () {
    const { categoryUuid } = this.$route.query;
    this.getManualAddStepInitDataFunc(categoryUuid)
  },
  methods: {
    handleReEditCategory () {
      const prompting = '切换类目后将重新编辑信息,您确认吗？';
      const title = '提示';
      this.$confirm(prompting, title, {
        type: 'warning',
      }).then(() => {
        this.$router.go(-1)
      }).catch(() => {})
    },
    getManualAddStepInitDataFunc (categoryUuid) {
      let data = { categoryUuid };
      let loadingInstance = getLoadingFn('basic_info_body');
      ApiRequest(
        '/sysback/addsingleproduct/basicinfo/toManualAddStep1',
        'post',
        data,
        true
      )
        .then((res) => {
          loadingInstance.close();
          this.saleAttributeLoadFinished = true;
          if (res.retStatus !== '1') {
            return false;
          }
          const {
            currentCategoryStr,
            categoryUuid,
            specList,
            productTypeOptions,
            templateUuid,
            basicInfoList,
            manageList,
            marketingList,
            taxList,
            logisticsList,
            sceneList
          } = res.retData;
          this.category.name = currentCategoryStr;
          this.category.uuid = categoryUuid;
          // this.basicInfo.productTypeOptions = productTypeOptions;
          // 选择商品类型 不让选择 项目商品 https://www.tapd.cn/41685229/prong/stories/view/1141685229001232400
          this.basicInfo.productTypeOptions = productTypeOptions.filter(item => item.optionValue !== '10')
          this.specList = specList;
          this.generateCode.templateUuid = templateUuid;
          this.generateCode.basicInfoList = basicInfoList;
          this.generateCode.manageInfoList = manageList;
          this.generateCode.marketingInfoList = marketingList;
          this.generateCode.taxInfoList = taxList;
          this.generateCode.logisticsInfoList = logisticsList;
          this.generateCode.sceneInfoList = sceneList;
        })
        .catch(() => {
          loadingInstance.close();
        });
    },
    getFormDataFn (data) {
      this.generateCode.formData = data;
    },
    getSpecListFn (data) {
      this.generateCode.specList = data;
    },
    /* 校验基础属性和销售属性 */
    async handleJudgeStep1 () {
      const flag = await this.$refs.basicInfoForm.handleTransferFormData();
      this.$refs.saleAttr.handleTransferSpecList();
      if (this.generateCode.specList.length === 0) {
        this.$message.warning('请完善销售属性');
        return false;
      }
      return flag;
    },
    /* 生成代码事件 */
    async handleGenerateCode () {
      const flag = await this.handleJudgeStep1();
      if (!flag) { return false };
      const params = {
        ...this.generateCode.formData,
        categoryUuid: this.category.uuid,
        templateUuid: this.generateCode.templateUuid,
        skuList: this.generateCode.specList
      };
      const hasBarCode = this.generateCode.formData.hasBarCode;
      if (!params.skuList || params.skuList.length == 0) {
        return;
      }
      // 判断商品条形码是否可以为空，以及是否超过最大允许填写的长度
      var isBarCodeEmpty = false;
      var isExceedLength = false;
      params.skuList.forEach(item => {
        if (!item.barcode) {
          isBarCodeEmpty = true;
        } else if (item.barcode.length > 300) {
          isExceedLength = true;
        }
      });
      if (hasBarCode && hasBarCode == '1' && isBarCodeEmpty) {
        // 如果品牌是有商品条形码的，sku生成时必须填写国际
        this.$message.error('请填写商品条形码');
        return;
      }
      if (isExceedLength) {
        this.$message.error('商品条形码长度不能超过300');
        return;
      }
      this.generateCodeAction(params).then(retData => {
        if (!retData) {
          return false;
        }
        this.$message.success('代码生成成功');
        this.$router.push({ name: 'commodityNotPerfection' })
        // const { spuNo, productUuid, skuNoMap } = retData;
        // const { mainUnit, mainUnitUuid, addPriceType } = this.generateCode.formData;
        // this.generateCode.isGenerate = true;
        // this.spuNo = spuNo;
        // this.productUuid = productUuid;
        // util.Pub.setStorageSync('productUuid', productUuid);
        // util.Pub.setStorageSync('spuNo', spuNo);
        // this.generateCode.packageList = {
        //   skuNoMap,
        //   mainUnit,
        //   mainUnitUuid,
        //   addPriceType
        // }
      });
    },
    handleToStep2 () {
      let vDom = this.$refs['attributeBody'];
      vDom.scrollIntoView({ behavior: 'smooth' });
    },
    /* 生成代码action */
    generateCodeAction (params) {
      return new Promise(resolve => {
        this.endingBtnLoading = true;
        ApiRequest(
          '/sysback/addsingleproduct/basicinfo/generateCode',
          'post',
          params,
          false
        ).then(res => {
          this.endingBtnLoading = false;
          if (!isResponseSuccess(res)) {
            resolve(false);
            return false;
          }
          resolve(res.retData);
        }).catch(() => {
          this.endingBtnLoading = false;
        })
      })
    },
    getManageAttributeDataFunc (list) {
      const {
        notSpecList,
        basicManageList,
        marketingList,
        taxList,
        logisticsList,
        sceneList
      } = list;
      this.submitCodeList = {
        notSpecList,
        basicManageList,
        marketingList,
        taxList,
        logisticsList,
        sceneList
      };
    },
    getPackageListFunc (list) {
      this.submitCodeList.packageList = list;
    },
    async handleSubmitData () {
      const flag = await this.handleJudgeStep1();
      if (!flag) { return false };
      this.$refs.manageAttr.getManageAttributesFn();
      this.$refs.skuAttr.getPackageListToApiFn();
      const data = {
        spuNo: this.spuNo,
        ...this.generateCode.formData,
        categoryUuid: this.category.uuid,
        templateUuid: this.generateCode.templateUuid,
        specList: this.generateCode.specList,
        ...this.submitCodeList
      };
      this.endingBtnLoading = true;
      ApiRequest(
        '/sysback/addsingleproduct/basicinfo/saveProductBasicInfo',
        'post',
        data,
        false
      ).then((res) => {
        this.endingBtnLoading = false;
        if (res.retStatus !== '1') {
          setWarningDialogFunc(this, res, this.$refs.manageAttr.resetSalePlatFunc);
          return false;
        }
        this.$message.success('基本信息保存成功');
        this.finishedFlag = true;
      });
    }
  }
};
</script>
<style lang="less" scoped>
.basic_info_body {
  overflow: auto !important
}
.title_wrap {
  margin: 10px 0px;
  div {
    margin: 0px 10px;
  }
}
.basic_info_form_body, .sale_attribute_body, .manage_attribute_body {
  margin-bottom: 10px;
}
</style>
